package com.jacky.concurrent.future;

import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: jacky
 * @date: 2018/6/21
 * Time: 11:45
 * Description:
 **/
public class FutureTaskDemo {

    /**
     * FutureTask方法
     * 1、 取消任务
     * boolean cancel(boolean mayInterruptIfRunning);
     * 2、是否已经取消
     * boolean isCancelled();
     * 3、是否已经完成
     * boolean isDone();
     * 4、取得返回对象
     * V get() throws InterruptedException, ExecutionException;
     * 5、取得返回对象, 并可以设置超时时间
     * V get(long timeout, TimeUnit unit)
     *
     * @param args
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return new RealData().costTime();
            }
        });
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(future);

        System.out.println("RealData方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData方法的结果
        System.out.println(future.get());
    }

    private static void doOtherThing() throws InterruptedException {
        Thread.sleep(2000L);
    }
}

class RealData {

    public String costTime() {
        try {
            // 模拟RealData耗时操作
            Thread.sleep(3000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }

}